<template>
  <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="工位备件" :visible.sync="dialogPvVisible" width="80%">
    <div style="background: #ffffff">
      <div class="filter-container">
        <el-form ref="dataForm" :model="listQuery"   label-width="80px" class="searchform" inline>

          <el-form-item :label="$t('bs.spareparts')" prop="spareparts">
            <el-input
              v-model="listQuery.spareparts"
              class="filter-item"
              :placeholder="$t('bs.spareparts')"
              style="width: 204px;"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
          <el-form-item :label="$t('bs.process')" prop="process">
            <el-input
              v-model="listQuery.process"
              class="filter-item"
              :placeholder="$t('bs.process')"
              style="width: 204px;"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
          <el-form-item :label="$t('bs.specification\n')" prop="specification">
            <el-input
              v-model="listQuery.specification"
              class="filter-item"
              :placeholder="$t('bs.specification\n')"
              style="width: 204px;"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
          <el-form-item :label="$t('bs.supplier')" prop="supplier">
            <el-input
              v-model="listQuery.supplier"
              class="filter-item"
              :placeholder="$t('bs.supplier')"
              style="width: 204px;"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item> <el-form-item :label="$t('bs.spm')" prop="url">
          <el-input
            v-model="listQuery.spm"
            class="filter-item"
            :placeholder="$t('bs.spm')"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
          <el-form-item :label="$t('bs.sap_code')" prop="sap_code">
            <el-input
              v-model="listQuery.sap_code"
              class="filter-item"
              :placeholder="$t('bs.sap_code')"
              style="width: 204px;"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
          <el-form-item :label="$t('bs.min_stock')" prop="min_stock">
            <el-input
              v-model="listQuery.min_stock"
              class="filter-item"
              :placeholder="$t('bs.min_stock')"
              style="width: 204px;"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
<!--          <el-form-item :label="$t('bs.station')" prop="station">-->
<!--            <el-select v-model="listQuery.st_id" filterable clearable placeholder="请选择工站" disabled>-->
<!--              <el-option-->
<!--                v-for="item in station_list"-->
<!--                :key="item.id"-->
<!--                :label="item.station_name"-->
<!--                :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->


<!--          </el-form-item>-->

          <el-form-item>
            <el-button v-waves class="filter-item" @click="handleFilter">
              {{ $t('table.search') }}
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" @click="handleFilterReset">
              {{$t('bs.reset')}}
            </el-button>
          </el-form-item>
        </el-form>

      </div>
      <div style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;">
        <div style="display: flex;flex-direction: row;padding-bottom: 24px">
          <div style="flex: 1;display: flex;align-items: center">
            <el-button
              class="filter-item"
              plain
              size="small"
              style="margin-left: 10px;"
              type="primary"
              @click="handleCreate"
            >
              {{ $t('table.add') }}
            </el-button>
            <el-button
              class="filter-item"
              plain
              size="small"
              style="margin-left: 10px;"
              type="primary"
              @click="handleDeleteAll"
            >
              {{$t('bs.batchDelete')}}
            </el-button>
          </div>
          <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
            <el-popover
              v-model="tablesetvisible"
              placement="bottom-start"
              width="160"
            >
              <div class="setcheckbox">
                <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
                <el-checkbox v-for="(item,key) in fileds" :key="key" v-model="item.is_show" false-label="0" true-label="1">
                  {{ item.title }}
                </el-checkbox>
              </div>
              <div slot="reference" class="hoverbutton">
                <img src="/static/table/fiter.png">
                <span style="margin-left: 8px;color: #666666">筛选</span>
              </div>
            </el-popover>
          </div>
        </div>
        <el-table
          key="id"
          v-loading="listLoading"
          :data="list"
          fit
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column v-if="fileds.name.is_show==1" :label="$t('bs.spareparts')">
            <template slot-scope="{row}">
              {{ row.name }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.process.is_show==1" :label="$t('bs.process')">
            <template slot-scope="{row}">
              {{ row.process }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.specification.is_show==1" :label="$t('bs.specification')">
            <template slot-scope="{row}">
              {{ row.specification }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.supplier.is_show==1" :label="$t('bs.supplier')">
            <template slot-scope="{row}">
              {{ row.supplier }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.spm.is_show==1" :label="$t('bs.spm')">
            <template slot-scope="{row}">
              {{ row.spm }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.sap_code.is_show==1" :label="$t('bs.sap_code')">
            <template slot-scope="{row}">
              {{ row.sap_code }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.min_stock.is_show==1" :label="$t('bs.min_stock')">
            <template slot-scope="{row}">
              {{ row.min_stock }}
            </template>
          </el-table-column>
          <el-table-column v-if="fileds.st_id.is_show==1" :label="$t('bs.station')">
            <template slot-scope="{row}">
              {{ row.station_name }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button circle icon="el-icon-edit" size="small" @click="handleUpdate(row)" />

              <el-popconfirm
                title="确定删除吗？"
                @confirm="handleDelete([row.id])"
              >
                <el-button slot="reference" style="margin-left: 8px" circle icon="el-icon-delete" size="small" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :limit.sync="listQuery.limit"
          :page.sync="listQuery.page_no"
          :total="total"
          @pagination="getList"
        />

      </div>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogPvVisible = false">
        {{ $t('table.cancel') }}
      </el-button>
<!--      <el-button type="primary" @click="subbj">-->
<!--        {{ $t('table.confirm') }}-->
<!--      </el-button>-->
    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-row :gutter="2">

          <el-col :span="12">
            <el-form-item :label="$t('bs.spareparts')" prop="spareparts">
              <el-input v-model="temp.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.process')" prop="process">
              <el-input v-model="temp.process" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.specification')" prop="specification">
              <el-input v-model="temp.specification" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.spm')" prop="spm">
              <el-input v-model="temp.spm" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.sap_code')" prop="sap_code">
              <el-input v-model="temp.sap_code" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.min_stock')" prop="min_stock">
              <el-input v-model="temp.min_stock" type="number" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item :label="$t('bs.station')" prop="station">-->
<!--              <el-select v-model="temp.st_id" filterable placeholder="请选择工站">-->
<!--                <el-option-->
<!--                  v-for="item in station_list"-->
<!--                  :key="item.id"-->
<!--                  :label="item.station_name"-->
<!--                  :value="item.id">-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </el-dialog>
</template>

<script>
import {fetchList, createData, updateData, delData, fetchOne} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect' // secondary package based on el-pagination

export default {
  name: 'spareView',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      station_list:[],
      multipleSelection:[],
      selectbj:false,
      total:0,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {

        }
      },
      queryMap:{},
      listLoading:false,
      list:[],
      fileds: {
        name: { filed: 'name', title: '关键备件', is_show: '1' },
        process: { filed: 'process', title: '工艺', is_show: '1' },
        specification: { filed: 'specification', title: '规格', is_show: '1' },
        supplier: { filed: 'supplier', title: '图片', is_show: '1' },
        spm: { filed: 'spm', title: 'SPM', is_show: '1' },
        sap_code: { filed: 'sap_code', title: 'sap编码', is_show: '1' },
        min_stock: { filed: 'min_stock', title: '最小库存', is_show: '1' },
        st_id: { filed: 'st_id', title: '工位', is_show: '1' },
      },
      checked: true,
      tablesetvisible: false,
      tableKey: 0,

      showReviewer: false,
      temp: {
        id: '', name: '', process: '', specification: '', supplier: '', spm: '', sap_code: '', min_stock: '', st_id: '' },


      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '关键备件名称不能为空', trigger: 'change' }],
      },
      downloadLoading: false

    }
  },
  mounted() {
  //  this.getList()
    this.getStationList();
  },
  methods: {
    show(id){
      this.listQuery.st_id=id;
      this.temp.st_id=id;
      console.log('查询条件',this.listQuery)
      this.handleFilter();
    },
    getStationList(){
      this.listLoading = true
      fetchList({  page_no: 1,
        limit: 100,
        sort: 'id',}, 'sl_view_station').then(response => {
        if (response.data && response.data.items) {
          this.station_list = response.data.items
        }
        this.listLoading = false
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(this.multipleSelection.map(item=>item.id))
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'spare_parts').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        st_id:this.listQuery.st_id,
        where: {}
      }
      this.handleFilter()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.dialogPvVisible=true;
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {  id: '', name: '', process: '', specification: '', supplier: '', spm: '', sap_code: '', min_stock: '', st_id: this.temp.st_id }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'spare_parts',
            add: this.temp
          }
          createData({ data: [data] }, 'spare_parts').then(() => {
            this.handleFilter()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'spare_parts',
            update: this.temp
          }
          updateData({ data: [data] }, 'spare_parts').then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
           this.handleFilter()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(ids) {
      console.log("执行删除")
      delData({ id: ids.join(',') }, 'spare_parts').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list=[];
        this.total=0;
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 268px;
}
</style>

